package org.springblade.tms.module.inquirysheet.base;

import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.mpobjects.bdparsii.eval.Expression;
import com.mpobjects.bdparsii.eval.Parser;
import com.mpobjects.bdparsii.eval.Scope;
import com.mpobjects.bdparsii.eval.Variable;
import com.mpobjects.bdparsii.tokenizer.ParseException;
import lombok.SneakyThrows;
import org.apache.logging.log4j.util.Strings;
import org.springblade.common.utils.EnumUtils;
import org.springblade.core.mp.support.Condition;
import org.springblade.core.mp.support.Query;
import org.springblade.core.secure.utils.AuthUtil;
import org.springblade.core.tool.api.R;
import org.springblade.core.tool.utils.BeanUtil;
import org.springblade.system.feign.IDictBizClient;
import org.springblade.tms.global.enums.*;
import org.springblade.tms.global.exception.CommonException;
import org.springblade.tms.global.utils.EmailUtil;
import org.springblade.tms.module.currencytype.entity.TMCurrencyType;
import org.springblade.tms.module.currencytype.service.ICurrencyTypeService;
import org.springblade.tms.module.historicalquotation.entity.TMHistoricalQuotation;
import org.springblade.tms.module.historicalquotation.service.IHistoricalQuotationService;
import org.springblade.tms.module.inquirycarrier.entity.TMInquiryCarrier;
import org.springblade.tms.module.inquirycarrier.service.IInquiryCarrierService;
import org.springblade.tms.module.inquirysheet.entity.TMInquirySheet;
import org.springblade.tms.module.inquirysheet.service.IInquirySheetService;
import org.springblade.tms.module.inquirysheet.vo.*;
import org.springblade.tms.module.offer.entity.TMOffer;
import org.springblade.tms.module.offer.service.IOfferService;
import org.springblade.tms.module.sap.base.SapRequestService;
import org.springblade.tms.module.userinfo.entity.TMUserInfo;
import org.springblade.tms.module.userinfo.service.IUserInfoService;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

import static cn.hutool.core.bean.BeanUtil.toBean;
import static org.springblade.common.constant.TenantConstant.DEFAULT_TENANT_ID;
import static org.springblade.tms.global.constant.DictCodeConstant.*;
import static org.springblade.tms.global.constant.RedisConstant.INQUIRY_FORM_VOID;

/**
 * @projectName: BladeX
 * @package: org.springblade.tms.module.inquirysheet.base
 * @className: InquirySheetService
 * @author: yr
 * @description: 询价单服务类
 * @date: 2022/6/23 14:29
 */
@Service
@Transactional
public class InquirySheetService {
    @Resource
    private IInquirySheetService iInquirySheetService;
    @Resource
    private IUserInfoService userInfoService;
    @Resource
    private IInquiryCarrierService iInquiryCarrierService;
    @Resource
    private IOfferService offerService;
    @Resource
    private IHistoricalQuotationService historicalQuotationService;
    @Resource
    private ICurrencyTypeService currencyTypeService;
    @Resource
    private IDictBizClient dictBizClient;
    @Resource
    private SapRequestService sapRequestService;
    @Resource
    private RedisTemplate redisTemplate;
    @Resource
    private EmailUtil emailUtil;

    /**
     * @param inquirySheetReqVo:
     * @param query:
     * @return R<IPage < InquirySheetRespVo>>
     * @author yr
     * @description 询价单列表查询
     * @date 2022/6/23 15:01
     */
    public R<IPage<InquirySheetRespVo>> list(InquirySheetReqVo inquirySheetReqVo, Query query) {
        Long userId = AuthUtil.getUser().getUserId();
        TMUserInfo userInfo = userInfoService.lambdaQuery().eq(TMUserInfo::getParentId, userId).one();
        List<Long> inquiryIds = new ArrayList<>();
        if (userInfo != null && userInfo.getUserType().equals(UserTypeEnum.CARRIER.getValue())) {
            List<TMInquiryCarrier> tmInquiryCarriers = iInquiryCarrierService.lambdaQuery()
                    .eq(TMInquiryCarrier::getCarrierId, userInfo.getTmId())
                    .isNull(TMInquiryCarrier::getShippingCompany)
                    .eq(Strings.isNotBlank(inquirySheetReqVo.getQuotationStatus()), TMInquiryCarrier::getQuotationStatus, inquirySheetReqVo.getQuotationStatus())
                    .list();
            List<Long> list = tmInquiryCarriers.stream().map(TMInquiryCarrier::getParentId).collect(Collectors.toList());
            inquiryIds.addAll(list);
        }
        LambdaQueryWrapper<TMInquirySheet> tmInquirySheetLambdaQueryWrapper = Condition.getQueryWrapper(new TMInquirySheet()).lambda()
                .like(Strings.isNotBlank(inquirySheetReqVo.getArrivalAddress()), TMInquirySheet::getArrivalAddress, inquirySheetReqVo.getArrivalAddress())
                .like(Strings.isNotBlank(inquirySheetReqVo.getGoodsClass()), TMInquirySheet::getGoodsClass, inquirySheetReqVo.getGoodsClass())
                .like(Strings.isNotBlank(inquirySheetReqVo.getShippingAddress()), TMInquirySheet::getShippingAddress, inquirySheetReqVo.getShippingAddress())
                .like(Strings.isNotBlank(inquirySheetReqVo.getArrivalEnterprise()), TMInquirySheet::getArrivalEnterprise, inquirySheetReqVo.getArrivalEnterprise())
                .like(Strings.isNotBlank(inquirySheetReqVo.getDeparturePort()), TMInquirySheet::getDeparturePort, inquirySheetReqVo.getArrivalAddress())
                .like(Strings.isNotBlank(inquirySheetReqVo.getDestinationPort()), TMInquirySheet::getDestinationPort, inquirySheetReqVo.getDestinationPort())
                .like(Strings.isNotBlank(inquirySheetReqVo.getGoodsType()), TMInquirySheet::getGoodsType, inquirySheetReqVo.getGoodsType())
                .like(Strings.isNotBlank(inquirySheetReqVo.getIndustry()), TMInquirySheet::getIndustry, inquirySheetReqVo.getIndustry())
                .like(Strings.isNotBlank(inquirySheetReqVo.getShippingEnterprise()), TMInquirySheet::getShippingEnterprise, inquirySheetReqVo.getShippingEnterprise())
                .like(Strings.isNotBlank(inquirySheetReqVo.getInvoiceNumber()), TMInquirySheet::getInvoiceNumber, inquirySheetReqVo.getInvoiceNumber())
                .eq(Strings.isNotBlank(inquirySheetReqVo.getQuoteStatus()), TMInquirySheet::getQuoteStatus, inquirySheetReqVo.getQuoteStatus())
                .like(Strings.isNotBlank(inquirySheetReqVo.getCpmc()), TMInquirySheet::getCpmc, inquirySheetReqVo.getCpmc())
                .in(!inquiryIds.isEmpty(), TMInquirySheet::getId, inquiryIds)
                .apply(userInfo != null && userInfo.getUserType().equals(UserTypeEnum.CARRIER.getValue()) && inquiryIds.isEmpty(), "1=2")
                .eq(TMInquirySheet::getWorkflowId, inquirySheetReqVo.getWorkflowId());
        if (userInfo != null && userInfo.getUserType().equals(UserTypeEnum.CARRIER.getValue())) {
            tmInquirySheetLambdaQueryWrapper.orderByDesc(TMInquirySheet::getUpdateTime, TMInquirySheet::getId);
        } else {
            tmInquirySheetLambdaQueryWrapper.orderByDesc(TMInquirySheet::getCreateTime, TMInquirySheet::getId);
        }
        IPage<TMInquirySheet> inquirySheetIPage = iInquirySheetService.page(Condition.getPage(query), tmInquirySheetLambdaQueryWrapper);
        List<InquirySheetRespVo> records = BeanUtil.copy(inquirySheetIPage.getRecords(), InquirySheetRespVo.class);
        if (userInfo != null && userInfo.getUserType().equals(UserTypeEnum.CARRIER.getValue())) {
            List<TMInquiryCarrier> tmInquiryCarriers = iInquiryCarrierService.lambdaQuery()
                    .eq(TMInquiryCarrier::getCarrierId, userInfo.getTmId())
                    .isNull(TMInquiryCarrier::getShippingCompany)
                    .list();
            Map<Long, String> quotationStatus = tmInquiryCarriers.stream().collect(Collectors.toMap(TMInquiryCarrier::getParentId, TMInquiryCarrier::getQuotationStatus));
            records.forEach(inquirySheetRespVo -> {
                inquirySheetRespVo.setQuotationStatus(EnumUtils.getEnumByValue(EnquiryStatusEnum.class, quotationStatus.get(inquirySheetRespVo.getId())).get().description());
            });
        }
        IPage<InquirySheetRespVo> pageVo = new Page(inquirySheetIPage.getCurrent(), inquirySheetIPage.getSize(), inquirySheetIPage.getTotal());
        records.forEach(inquirySheetRespVo -> {
            inquirySheetRespVo.setQuoteStatus(EnumUtils.getEnumByValue(InquiryStatusEnum.class, inquirySheetRespVo.getQuoteStatus()).get().description());
        });
        pageVo.setRecords(records);
        return R.data(pageVo);
    }

    /**
     * @param id:
     * @return R<IPage < InquirySheetRespVo>>
     * @author yr
     * @description 询价单列表详情
     * @date 2022/6/23 15:01
     */
    public R<InquirySheetRespVo> detail(Long id) {
        TMInquirySheet inquirySheet = iInquirySheetService.getById(id);
        InquirySheetRespVo inquirySheetRespVo = BeanUtil.copy(inquirySheet, InquirySheetRespVo.class);
        Long userId = AuthUtil.getUser().getUserId();
        TMUserInfo userInfo = userInfoService.lambdaQuery().eq(TMUserInfo::getParentId, userId).one();
        if (userInfo != null && userInfo.getUserType().equals(UserTypeEnum.CARRIER.getValue())) {
            TMInquiryCarrier tmInquiryCarrier = iInquiryCarrierService.lambdaQuery()
                    .eq(TMInquiryCarrier::getCarrierId, userInfo.getTmId())
                    .eq(TMInquiryCarrier::getParentId, id)
                    .isNull(TMInquiryCarrier::getShippingCompany)
                    .one();
            inquirySheetRespVo.setDetailId(tmInquiryCarrier.getId());
            inquirySheetRespVo.setQuotationStatus(EnumUtils.getEnumByValue(EnquiryStatusEnum.class, tmInquiryCarrier.getQuotationStatus()).get().description());
        }
        return R.data(inquirySheetRespVo);
    }

    /**
     * @param inquiryCarrierListReqVo:
     * @return R<IPage < InquirySheetRespVo>>
     * @author yr
     * @description 询价单承运商列表
     * @date 2022/6/23 15:01
     */
    public R<IPage<InquiryCarrierListRespVo>> carrier(InquiryCarrierListReqVo inquiryCarrierListReqVo, Query query) {
        List<String> carrierTMIds = iInquiryCarrierService.lambdaQuery().eq(TMInquiryCarrier::getParentId, inquiryCarrierListReqVo.getInquiryId())
                .list().stream().map(TMInquiryCarrier::getCarrierId).collect(Collectors.toList());
        IPage<TMUserInfo> tmUserInfoIPage = userInfoService.page(Condition.getPage(query), Condition.getQueryWrapper(new TMUserInfo())
                .lambda().eq(TMUserInfo::getUserType, UserTypeEnum.CARRIER.getValue())
                .like(Strings.isNotBlank(inquiryCarrierListReqVo.getName()), TMUserInfo::getName, inquiryCarrierListReqVo.getName())
                .like(Strings.isNotBlank(inquiryCarrierListReqVo.getPhone()), TMUserInfo::getPhone, inquiryCarrierListReqVo.getPhone())
                .like(Strings.isNotBlank(inquiryCarrierListReqVo.getCarrierGroup()), TMUserInfo::getCarrierGroup, inquiryCarrierListReqVo.getCarrierGroup())
                .like(Strings.isNotBlank(inquiryCarrierListReqVo.getTmId()), TMUserInfo::getTmId, inquiryCarrierListReqVo.getTmId())
                .notIn(!carrierTMIds.isEmpty(), TMUserInfo::getTmId, carrierTMIds));
        List<InquiryCarrierListRespVo> records = BeanUtil.copy(tmUserInfoIPage.getRecords(), InquiryCarrierListRespVo.class);
        IPage<InquiryCarrierListRespVo> pageVo = new Page(tmUserInfoIPage.getCurrent(), tmUserInfoIPage.getSize(), tmUserInfoIPage.getTotal());
        pageVo.setRecords(records);
        return R.data(pageVo);
    }

    /**
     * @param bindCarrierVo :
     * @return R<IPage < InquirySheetRespVo>>
     * @author yr
     * @description 询价单承运商绑定
     * @date 2022/6/23 15:01
     */
    public R<Boolean> bind(BindCarrierVo bindCarrierVo) {
        if (bindCarrierVo.getEndTime() >= bindCarrierVo.getValidityPeriod()) {
            CommonException.throwCommonException("询价有效期必须大于询价响应截止日期");
        }
        List<TMInquiryCarrier> list = iInquiryCarrierService.lambdaQuery()
                .in(TMInquiryCarrier::getCarrierId, bindCarrierVo.getCarrierId())
                .eq(TMInquiryCarrier::getParentId, Long.valueOf(bindCarrierVo.getInquiryId()))
                .list();
        if (!list.isEmpty()){
            CommonException.throwCommonException("存在承运商已绑定该询价单");
        }
        TMInquirySheet tmInquirySheet = iInquirySheetService.getById(bindCarrierVo.getInquiryId());
        List<TMUserInfo> tmUserInfo = userInfoService.lambdaQuery().in(TMUserInfo::getTmId, bindCarrierVo.getCarrierId()).list();
        ArrayList<TMInquiryCarrier> inquiryCarriers = new ArrayList<>();
        tmUserInfo.forEach(tmUserInfo1 -> {
            TMInquiryCarrier tmInquiryCarrier = new TMInquiryCarrier();
            tmInquiryCarrier.setCarrierId(tmUserInfo1.getTmId());
            tmInquiryCarrier.setCarrierName(tmUserInfo1.getName());
            tmInquiryCarrier.setParentId(Long.valueOf(bindCarrierVo.getInquiryId()));
            tmInquiryCarrier.setQuotationStatus(EnquiryStatusEnum.TO_BE_QUOTED.value());
            inquiryCarriers.add(tmInquiryCarrier);
        });
        boolean save = iInquiryCarrierService.saveBatch(inquiryCarriers);
        R<String> value = dictBizClient.getValue(SYSTEM_CONFIG, MAXIMUM_NUMBER_OF_CARRIERS);
        String data = value.getData();
        List<TMInquiryCarrier> tmInquiryCarriers = iInquiryCarrierService.lambdaQuery()
                .eq(TMInquiryCarrier::getParentId, bindCarrierVo.getInquiryId())
                .isNull(TMInquiryCarrier::getShippingCompany)
                .list();
        if (tmInquiryCarriers.size() > Integer.parseInt(data)) {
            CommonException.throwCommonException("分配失败，已达到可分配承运商最大数");
        }
        tmInquirySheet.setEndTime(LocalDateTime.now().plusHours(bindCarrierVo.getEndTime()));
        tmInquirySheet.setEffectiveTime(LocalDateTime.now().plusHours(bindCarrierVo.getValidityPeriod()));
        tmInquirySheet.setWhetherToAllocate(BigDecimal.valueOf(WhetherEnum.yes.getValue()));
        tmInquirySheet.setRemark(bindCarrierVo.getRemark());
        tmInquirySheet.setQuoteStatus(InquiryStatusEnum.TO_BE_CONFIRMED.value());
        iInquirySheetService.updateById(tmInquirySheet);
        redisTemplate.opsForValue().set(INQUIRY_FORM_VOID + ExpirationReasonEnum.EXCEEDED_THE_VALIDITY_PERIOD_OF_THE_INQUIRY.getValue() + ":" + tmInquirySheet.getId(),
                null, org.springblade.core.tool.utils.DateUtil.toDate(tmInquirySheet.getEffectiveTime()).getTime() - new Date().getTime(), TimeUnit.MILLISECONDS);
        redisTemplate.opsForValue().set(INQUIRY_FORM_VOID + ExpirationReasonEnum.RESPONSE_DEADLINE_EXCEEDED.getValue() + ":" + tmInquirySheet.getId(),
                null, org.springblade.core.tool.utils.DateUtil.toDate(tmInquirySheet.getEndTime()).getTime() - new Date().getTime(), TimeUnit.MILLISECONDS);
        String title = dictBizClient.getValue(SYSTEM_CONFIG, EMAIL_TITLE, DEFAULT_TENANT_ID).getData();
        String msg = dictBizClient.getValue(SYSTEM_CONFIG, EMAIL_MSG, DEFAULT_TENANT_ID).getData();
        tmUserInfo.forEach(userInfo -> {
            if (Strings.isNotBlank(userInfo.getMailbox())) {
                ListUtil.toList(userInfo.getMailbox().split(",")).forEach(mailbox -> {
                    emailUtil.sendMessage(mailbox, title, msg);
                });
            }
        });
        return R.status(save);
    }

    /**
     * @param inquiryItemSaveVo:
     * @return R<Boolean>
     * @author yr
     * @description 承运商报价
     * @date 2022/6/24 16:17
     */
    public R<Boolean> quotedPrice(InquiryItemSaveVo inquiryItemSaveVo, Long id, Long startId) {
        TMInquiryCarrier tmInquiryCarrier = iInquiryCarrierService.getById(id);
        //判断是否超过最大船公司数
        List<TMInquiryCarrier> tmInquiryCarriers = iInquiryCarrierService.lambdaQuery()
                .eq(TMInquiryCarrier::getCarrierId, tmInquiryCarrier.getCarrierId())
                .eq(TMInquiryCarrier::getParentId, tmInquiryCarrier.getParentId())
                .isNotNull(TMInquiryCarrier::getShippingCompany)
                .list();
        R<String> value = dictBizClient.getValue(SYSTEM_CONFIG, MAXIMUM_NUMBER_OF_SHIPPING);
        String data = value.getData();
        if (tmInquiryCarriers.size() >= Integer.parseInt(data)) {
            CommonException.throwCommonException("分配失败，已达到可分配船公司最大数");
        }
        Map<String, Object> stringObjectMap = BeanUtil.toMap(inquiryItemSaveVo);
        if (Strings.isNotBlank(inquiryItemSaveVo.getShippingCompany())) {
            if (!Strings.isNotBlank(tmInquiryCarrier.getShippingCompany())) {
                tmInquiryCarrier.setId(null);
            }
            tmInquiryCarrier.setShippingCompany(inquiryItemSaveVo.getShippingCompany());
            tmInquiryCarrier.setQuotationStatus(EnquiryStatusEnum.TO_BE_CONFIRMED.value());
            iInquiryCarrierService.saveOrUpdate(tmInquiryCarrier);
        }
        ArrayList<TMOffer> offers = new ArrayList<>();
        stringObjectMap.forEach((k, v) -> {
            if (Strings.isNotBlank((String) v)) {
                TMOffer tmOffer = new TMOffer();
                tmOffer.setFieldName(k);
                tmOffer.setParentId(tmInquiryCarrier.getId());
                tmOffer.setValue((String) v);
                offers.add(tmOffer);
            }
        });
        List<TMOffer> tmOffers = offerService.lambdaQuery().eq(TMOffer::getParentId, id).list();
        //删除之前的报价，新增历史记录
        HashMap<String, String> offerMap = new HashMap<>();
        offers.forEach(tmOffer -> {
            offerMap.put(tmOffer.getFieldName(), tmOffer.getValue());
        });
        InquiryItemSaveVo inquiryItemSave = toBean(offerMap, InquiryItemSaveVo.class);
        String toJsonStr = JSONUtil.toJsonStr(inquiryItemSave);
        TMHistoricalQuotation tmHistoricalQuotation = new TMHistoricalQuotation();
        tmHistoricalQuotation.setParentId(tmInquiryCarrier.getId());
        tmHistoricalQuotation.setBidder(tmInquiryCarrier.getCarrierName());
        tmHistoricalQuotation.setQuotationTime(LocalDateTime.now());
        tmHistoricalQuotation.setQuotation(toJsonStr);
        historicalQuotationService.save(tmHistoricalQuotation);
        if (!tmOffers.isEmpty()) {
            offerService.deleteLogic(tmOffers.stream().map(TMOffer::getId).collect(Collectors.toList()));
        }
        //修改报价状态
        TMInquiryCarrier InquiryCarrier = iInquiryCarrierService.getById(startId);
        InquiryCarrier.setQuotationStatus(EnquiryStatusEnum.TO_BE_CONFIRMED.value());
        iInquiryCarrierService.updateById(InquiryCarrier);
        return R.status(offerService.saveBatch(offers));
    }

    /**
     * @param id:
     * @return R<Boolean>
     * @author yr
     * @description 报价查询
     * @date 2022/6/27 11:24
     */
    public R<List<InquiryItemQueryVo>> priceList(Long id) {
        List<TMInquiryCarrier> tmInquiryCarriers = iInquiryCarrierService.lambdaQuery()
                .eq(TMInquiryCarrier::getParentId, id)
                .isNull(TMInquiryCarrier::getShippingCompany)
                .list();
        if (tmInquiryCarriers.isEmpty()) {
            return R.data(new ArrayList<>());
        }
        return getPriceList(tmInquiryCarriers);
    }


    //获取报价列表通用方法
    @SneakyThrows
    private R<List<InquiryItemQueryVo>> getPriceList(List<TMInquiryCarrier> tmInquiryCarriers) {
        Long parentId = tmInquiryCarriers.get(0).getParentId();
        TMInquirySheet tmInquirySheet = iInquirySheetService.getById(parentId);
        List<InquiryItemQueryVo> inquiryItemQueryVos = BeanUtil.copy(tmInquiryCarriers, InquiryItemQueryVo.class);
        Map<Long, List<InquiryItemQueryVo>> inquiryItemIdMap = inquiryItemQueryVos.stream().collect(Collectors.groupingBy(InquiryItemQueryVo::getId));
        List<Long> ids = inquiryItemQueryVos.stream().map(InquiryItemQueryVo::getId).collect(Collectors.toList());
        List<TMOffer> tmOfferList = offerService.lambdaQuery().in(TMOffer::getParentId, ids).list();
        Map<Long, List<TMOffer>> offerMapToId = tmOfferList.stream().collect(Collectors.groupingBy(TMOffer::getParentId));
        offerMapToId.forEach((k, v) -> {
            HashMap<String, String> offerMap = new HashMap<>();
            v.forEach(tmOffer -> {
                offerMap.put(tmOffer.getFieldName(), tmOffer.getValue());
            });
            InquiryItemQueryVo inquiryItemQueryVo = inquiryItemIdMap.get(k).get(0);
            BeanUtil.copyNonNull(offerMap, inquiryItemQueryVo);
        });
        //获取当前用户
        Long userId = AuthUtil.getUser().getUserId();
        TMUserInfo tmUserInfo = userInfoService.lambdaQuery().eq(TMUserInfo::getParentId, userId).one();
        //外贸排名所需数据
        List<Long> parentIds = tmInquiryCarriers.stream().map(TMInquiryCarrier::getParentId).collect(Collectors.toList());
        List<String> carrierIds = tmInquiryCarriers.stream().map(TMInquiryCarrier::getCarrierId).collect(Collectors.toList());
        //取出该询价单外贸所有报价
        List<TMInquiryCarrier> InquiryCarriers = iInquiryCarrierService.lambdaQuery()
                .in(TMInquiryCarrier::getParentId, parentIds)
                .in(TMInquiryCarrier::getCarrierId, carrierIds)
                .isNotNull(TMInquiryCarrier::getShippingCompany)
                .list();
        Map<String, List<TMInquiryCarrier>> inquiryCarrierByCarrierId = InquiryCarriers.stream().collect(Collectors.groupingBy(TMInquiryCarrier::getCarrierId));
        List<Long> inquiryCarrierIds = InquiryCarriers.stream().map(TMInquiryCarrier::getId).collect(Collectors.toList());
        List<TMOffer> tmOffers = offerService.lambdaQuery().in(!inquiryCarrierIds.isEmpty(), TMOffer::getParentId, inquiryCarrierIds).list();
        Map<Long, List<TMOffer>> offerByParentId = tmOffers.stream().collect(Collectors.groupingBy(TMOffer::getParentId));
        TMCurrencyType currencyType = currencyTypeService.lambdaQuery().eq(TMCurrencyType::getName, "USD").one();
        BigDecimal typeRate = currencyType.getRate();
        Scope scope = new Scope();
        Variable rate = scope.getVariable("rate");
        Expression expr = Parser.parse("shippingFee * rate + portCharges", scope);
        rate.setValue(typeRate);
        int compareTo = tmInquirySheet.getEndTime().compareTo(LocalDateTime.now());

        inquiryItemQueryVos.forEach(inquiryItemQueryVo -> {
            inquiryItemQueryVo.setQuotationStatus(EnumUtils.getEnumByValue(EnquiryStatusEnum.class, inquiryItemQueryVo.getQuotationStatus()).get().description());
            //报价排名
            if (Strings.isNotBlank(inquiryItemQueryVo.getQuotedPrice())) {
                inquiryItemQueryVo.setFieldsForRanking(BigDecimal.valueOf(Long.parseLong(inquiryItemQueryVo.getQuotedPrice())));
            } else if (Strings.isNotBlank(inquiryItemQueryVo.getQuotedPrice1())) {
                inquiryItemQueryVo.setFieldsForRanking(BigDecimal.valueOf(Long.parseLong(inquiryItemQueryVo.getQuotedPrice1())));
            } else {
                if (InquiryCarriers.isEmpty()) {
                    inquiryItemQueryVo.setFieldsForRanking(BigDecimal.valueOf(0));
                    return;
                }
                List<TMInquiryCarrier> inquiryCarriers = inquiryCarrierByCarrierId.get(inquiryItemQueryVo.getCarrierId());
                ArrayList<InquiryItemQueryVo> inquiryItemQueryVoArrayList = new ArrayList<>();
                if (inquiryCarriers == null) {
                    inquiryItemQueryVo.setFieldsForRanking(BigDecimal.valueOf(0));
                    return;
                }
                inquiryCarriers.forEach(tmInquiryCarrier -> {
                    List<TMOffer> offers = offerByParentId.get(tmInquiryCarrier.getId());
                    if (offers != null) {
                        HashMap<String, Object> hashMap = new HashMap<>();
                        for (TMOffer tmOffer : offers) {
                            hashMap.put(tmOffer.getFieldName(), tmOffer.getValue());
                        }
                        InquiryItemQueryVo itemQueryVo = BeanUtil.toBean(hashMap, InquiryItemQueryVo.class);
                        inquiryItemQueryVoArrayList.add(itemQueryVo);
                    }
                });
                if (!inquiryItemQueryVoArrayList.isEmpty()) {
                    InquiryItemQueryVo itemQueryVo = inquiryItemQueryVoArrayList.stream().min((a, b) -> {
                        //根据公式得出值然后得出最小运费
                        Variable shippingFee = scope.getVariable("shippingFee");
                        shippingFee.setValue(BigDecimal.valueOf(Long.parseLong(a.getShippingFee())));
                        Variable portCharges = scope.getVariable("portCharges");
                        portCharges.setValue(BigDecimal.valueOf(Long.parseLong(a.getPortCharges())));
                        BigDecimal evaluateA = expr.evaluate();
                        shippingFee.setValue(BigDecimal.valueOf(Long.parseLong(b.getShippingFee())));
                        portCharges.setValue(BigDecimal.valueOf(Long.parseLong(b.getPortCharges())));
                        BigDecimal evaluateB = expr.evaluate();
                        return evaluateA.compareTo(evaluateB);
                    }).get();
                    //得出报价用于排序
                    Variable shippingFee = scope.getVariable("shippingFee");
                    shippingFee.setValue(BigDecimal.valueOf(Long.parseLong(itemQueryVo.getShippingFee())));
                    Variable portCharges = scope.getVariable("portCharges");
                    portCharges.setValue(BigDecimal.valueOf(Long.parseLong(itemQueryVo.getPortCharges())));
                    BigDecimal evaluate = expr.evaluate();
                    inquiryItemQueryVo.setFieldsForRanking(evaluate);
                } else {
                    inquiryItemQueryVo.setFieldsForRanking(BigDecimal.valueOf(0));
                }
            }

        });
        if (compareTo < 0) {
            if (inquiryItemQueryVos.size() > 1) {
                inquiryItemQueryVos = inquiryItemQueryVos.stream()
                        .sorted(Comparator.comparing(InquiryItemQueryVo::getFieldsForRanking))
                        .collect(Collectors.toList());
            }
        }
        inquiryItemQueryVos.forEach(inquiryItemQueryVo -> {
            inquiryItemQueryVo.setFieldsForRanking(inquiryItemQueryVo.getFieldsForRanking().stripTrailingZeros());

            if (tmUserInfo != null && tmUserInfo.getUserType().equals(UserTypeEnum.CARRIER.getValue())) {
                if (tmUserInfo.getTmId().equals(inquiryItemQueryVo.getCarrierId())) {
                    return;
                }
                setInquiryItem(inquiryItemQueryVo);
            } else {
                if (compareTo > 0) {
                    setInquiryItem(inquiryItemQueryVo);
                }
            }
        });
        inquiryItemQueryVos.forEach(inquiryItemQueryVo -> {
            if (tmUserInfo != null && inquiryItemQueryVo.getCarrierId().equals(tmUserInfo.getTmId())) {
                inquiryItemQueryVo.setIsNotMy(true);
            }
            //处理合计字段的小数点
        });
        return R.data(inquiryItemQueryVos);
    }

    //将报价改为*
    private void setInquiryItem(InquiryItemQueryVo inquiryItemQueryVo) {
        inquiryItemQueryVo.setQuotedPrice("*");
        inquiryItemQueryVo.setAdjustOffer("*");
        inquiryItemQueryVo.setQuoteDescription("*");
        inquiryItemQueryVo.setRemark("*");
        inquiryItemQueryVo.setQuotedPrice1("*");
        inquiryItemQueryVo.setQuotedPrice2("*");
        inquiryItemQueryVo.setQuotedPrice3("*");
        inquiryItemQueryVo.setQuotedPrice4("*");
        inquiryItemQueryVo.setQuotedPrice5("*");
        inquiryItemQueryVo.setQuotedPrice6("*");
        inquiryItemQueryVo.setQuotedPrice7("*");
        inquiryItemQueryVo.setQuotedPrice8("*");
        inquiryItemQueryVo.setShippingCompany("*");
        inquiryItemQueryVo.setShippingFee("*");
        inquiryItemQueryVo.setPortCharges("*");
        inquiryItemQueryVo.setShippingDateETD("*");
        inquiryItemQueryVo.setScheduleEta("*");
        inquiryItemQueryVo.setDeparturePortBoxAngel("*");
        inquiryItemQueryVo.setDestinationPortBoxAngel("*");
        inquiryItemQueryVo.setIsItDirect("*");
        inquiryItemQueryVo.setTotal("*");
    }

    /**
     * @param id:
     * @return R<Boolean>
     * @author yr
     * @description 报价详情查询
     * @date 2022/6/27 11:24
     */
    public R<List<InquiryItemQueryVo>> priceDetailList(Long id, String carrierId) {
        List<TMInquiryCarrier> tmInquiryCarriers = iInquiryCarrierService.lambdaQuery()
                .eq(TMInquiryCarrier::getParentId, id)
                .eq(Strings.isNotBlank(carrierId), TMInquiryCarrier::getCarrierId, carrierId)
                .isNotNull(TMInquiryCarrier::getShippingCompany)
                .list();
        if (tmInquiryCarriers.isEmpty()) {
            return R.data(new ArrayList<>());
        }
        List<InquiryItemQueryVo> itemQueryVos = getPriceList(tmInquiryCarriers).getData();
        itemQueryVos.forEach(inquiryItemQueryVo -> {
            if (inquiryItemQueryVo.getShippingFee().equals("*")){
                return;
            }
            //排序
            TMCurrencyType currencyType = currencyTypeService.lambdaQuery().eq(TMCurrencyType::getName, "USD").one();
            BigDecimal typeRate = currencyType.getRate();
            Scope scope = new Scope();
            Variable rate = scope.getVariable("rate");
            Expression expr = null;
            try {
                expr = Parser.parse("shippingFee * rate + portCharges", scope);
            } catch (ParseException e) {
                CommonException.throwCommonException("合计公式格式错误");
            }
            rate.setValue(typeRate);
            Variable shippingFee = scope.getVariable("shippingFee");
            shippingFee.setValue(BigDecimal.valueOf(Long.parseLong(inquiryItemQueryVo.getShippingFee())));
            Variable portCharges = scope.getVariable("portCharges");
            portCharges.setValue(BigDecimal.valueOf(Long.parseLong(inquiryItemQueryVo.getPortCharges())));
            BigDecimal total = expr.evaluate();
            inquiryItemQueryVo.setTotal(total.toPlainString());
        });
        List<InquiryItemQueryVo> inquiryItemQueryVos = itemQueryVos.stream().sorted(Comparator.comparing(InquiryItemQueryVo::getTotal)).collect(Collectors.toList());
        return R.data(inquiryItemQueryVos);
    }

    /**
     * @param inquiryItemSaveVo:
     * @param id:
     * @return R<Boolean>
     * @author yr
     * @description 管理员报价接口
     * @date 2022/6/27 18:01
     */
    public R<Boolean> quotedPriceByAdmin(InquiryItemSaveVo inquiryItemSaveVo, Long id, Long startId) {
        TMInquiryCarrier tmInquiryCarrier = iInquiryCarrierService.getById(startId);
        inquiryItemSaveVo.setQuotedPrice(inquiryItemSaveVo.getAdjustOffer());
        tmInquiryCarrier.setQuotationStatus(EnquiryStatusEnum.PENDING.value());
        iInquiryCarrierService.updateById(tmInquiryCarrier);
        String toJsonStr = JSONUtil.toJsonStr(inquiryItemSaveVo);
        TMHistoricalQuotation tmHistoricalQuotation = new TMHistoricalQuotation();
        tmHistoricalQuotation.setParentId(id);
        tmHistoricalQuotation.setBidder(UserTypeEnum.ADMIN.getDescription());
        tmHistoricalQuotation.setQuotationTime(LocalDateTime.now());
        tmHistoricalQuotation.setQuotation(toJsonStr);
        if (Strings.isNotBlank(inquiryItemSaveVo.getAdjustOffer())) {
            TMOffer tmOffer = new TMOffer();
            tmOffer.setFieldName("adjustOffer");
            tmOffer.setValue(inquiryItemSaveVo.getAdjustOffer());
            tmOffer.setParentId(id);
            offerService.save(tmOffer);
        }
        return R.status(historicalQuotationService.save(tmHistoricalQuotation));
    }

    /**
     * @param id:
     * @return R<List < InquiryItemQueryVo>>
     * @author yr
     * @description 历史报价列表查询
     * @date 2022/6/27 18:06
     */
    public R<List<HistoricalQuotationVO>> historicalPriceList(Long id) {
        List<TMHistoricalQuotation> tmHistoricalQuotations = historicalQuotationService.lambdaQuery().eq(TMHistoricalQuotation::getParentId, id).list();
        List<HistoricalQuotationVO> historicalQuotationVOS = BeanUtil.copy(tmHistoricalQuotations, HistoricalQuotationVO.class);
        return R.data(historicalQuotationVOS);
    }

    //询价单作废
    public void expired(String expiredKey) {
        String[] split = expiredKey.split(":");
        ArrayList<String> keyList = ListUtil.toList(split);
        List<TMInquiryCarrier> tmInquiryCarriers = iInquiryCarrierService.lambdaQuery()
                .isNull(TMInquiryCarrier::getShippingCompany)
                .ne(TMInquiryCarrier::getQuotationStatus, EnquiryStatusEnum.FINISH.value())
                .ne(TMInquiryCarrier::getQuotationStatus, EnquiryStatusEnum.ABOLISHED.value())
                .ne(TMInquiryCarrier::getQuotationStatus, EnquiryStatusEnum.DID_NOT_WIN_THE_BID.value())
                .eq(TMInquiryCarrier::getParentId, Long.valueOf(keyList.get(3))).list();
        //超出询价有效期直接做废
        if (keyList.get(2).equals(ExpirationReasonEnum.EXCEEDED_THE_VALIDITY_PERIOD_OF_THE_INQUIRY.getValue())) {
            if (tmInquiryCarriers.isEmpty()) {
                return;
            }
            tmInquiryCarriers.forEach(tmInquiryCarrier -> {
                tmInquiryCarrier.setQuotationStatus(EnquiryStatusEnum.ABOLISHED.value());
            });
//            sapRequestService.quotedPrice(Long.valueOf(keyList.get(3)));
            //超出响应截止日期响应判断承运商是否未报价
        } else if (keyList.get(2).equals(ExpirationReasonEnum.RESPONSE_DEADLINE_EXCEEDED.getValue())) {
            TMInquirySheet tmInquirySheet = iInquirySheetService.getById(Long.valueOf(keyList.get(3)));
            if (tmInquirySheet.getWorkflowId().equals(EnquiryTypeEnum.foreignTrade.getValue())) {
                List<TMInquiryCarrier> inquiryCarriers = iInquiryCarrierService.lambdaQuery()
                        .isNotNull(TMInquiryCarrier::getShippingCompany)
                        .eq(TMInquiryCarrier::getParentId, Long.valueOf(keyList.get(3))).list();
                Map<String, List<TMInquiryCarrier>> collect = inquiryCarriers.stream().collect(Collectors.groupingBy(TMInquiryCarrier::getCarrierId));
                tmInquiryCarriers.forEach(inquiryCarrier -> {
                    if (collect.get(inquiryCarrier.getCarrierId()) == null) {
                        inquiryCarrier.setQuotationStatus(EnquiryStatusEnum.ABOLISHED.value());
                    }
                });
            } else {
                List<Long> ids = tmInquiryCarriers.stream().map(TMInquiryCarrier::getId).collect(Collectors.toList());
                List<TMOffer> tmOffers = offerService.lambdaQuery().in(TMOffer::getParentId, ids).list();
                Map<Long, List<TMOffer>> offerMapByParentId = tmOffers.stream().collect(Collectors.groupingBy(TMOffer::getParentId));
                //用于判断是否上报sap
                AtomicInteger isReported = new AtomicInteger();
                tmInquiryCarriers.forEach(tmInquiryCarrier -> {
                    if (offerMapByParentId.get(tmInquiryCarrier.getId()) == null) {
                        tmInquiryCarrier.setQuotationStatus(EnquiryStatusEnum.ABOLISHED.value());
                        isReported.getAndIncrement();
                    }
                });
                //如果作废数量等于查询出的未完成
                if (isReported.get() == tmInquiryCarriers.size()) {
//                    sapRequestService.quotedPrice(Long.valueOf(keyList.get(3)));
                }
            }
        }
        iInquiryCarrierService.updateBatchById(tmInquiryCarriers);
    }

    /**
     * @param id:
     * @return R<Boolean>
     * @author yr
     * @description 未中标
     * @date 2022/7/5 11:35
     */
    public R<Boolean> didNotWinTheBid(Long id) {
        TMInquiryCarrier tmInquiryCarrier = iInquiryCarrierService.getById(id);
        tmInquiryCarrier.setQuotationStatus(EnquiryStatusEnum.DID_NOT_WIN_THE_BID.value());
        boolean updateById = iInquiryCarrierService.updateById(tmInquiryCarrier);
        TMInquirySheet inquirySheet = iInquirySheetService.getById(tmInquiryCarrier.getParentId());
        if (inquirySheet.getWorkflowId().equals(EnquiryTypeEnum.foreignTrade.getValue())) {
            List<TMInquiryCarrier> tmInquiryCarriers = iInquiryCarrierService.lambdaQuery()
                    .eq(TMInquiryCarrier::getParentId, tmInquiryCarrier.getParentId())
                    .eq(TMInquiryCarrier::getCarrierId, tmInquiryCarrier.getCarrierId())
                    .isNotNull(TMInquiryCarrier::getShippingCompany)
                    .list();
            List<TMInquiryCarrier> inquiryCarriers = tmInquiryCarriers.stream().filter(inquiryCarrier -> {
                return !(inquiryCarrier.getQuotationStatus().equals(EnquiryStatusEnum.FINISH.value()) ||
                        inquiryCarrier.getQuotationStatus().equals(EnquiryStatusEnum.DID_NOT_WIN_THE_BID.value()));
            }).collect(Collectors.toList());
            if (!inquiryCarriers.isEmpty()) {
                return R.status(true);
            }
            TMInquiryCarrier inquiryCarrier = iInquiryCarrierService.lambdaQuery()
                    .eq(TMInquiryCarrier::getParentId, tmInquiryCarrier.getParentId())
                    .eq(TMInquiryCarrier::getCarrierId, tmInquiryCarrier.getCarrierId())
                    .isNull(TMInquiryCarrier::getShippingCompany)
                    .one();
            inquiryCarrier.setQuotationStatus(EnquiryStatusEnum.FINISH.value());
            iInquiryCarrierService.updateById(inquiryCarrier);
        }
        return R.data(updateById);
    }

    /**
     * @param id:
     * @return R<Boolean>
     * @author yr
     * @description 中标
     * @date 2022/7/5 11:35
     */
    public R<Boolean> winningTheBid(Long id, BigDecimal winningBoxQuantity) {
        TMInquiryCarrier tmInquiryCarrier = iInquiryCarrierService.getById(id);
        tmInquiryCarrier.setWinningBoxQuantity(winningBoxQuantity);
        tmInquiryCarrier.setQuotationStatus(EnquiryStatusEnum.FINISH.value());
        boolean updateById = iInquiryCarrierService.updateById(tmInquiryCarrier);
        TMInquirySheet inquirySheet = iInquirySheetService.getById(tmInquiryCarrier.getParentId());
        if (inquirySheet.getWorkflowId().equals(EnquiryTypeEnum.foreignTrade.getValue())) {
            List<TMInquiryCarrier> tmInquiryCarriers = iInquiryCarrierService.lambdaQuery()
                    .eq(TMInquiryCarrier::getParentId, tmInquiryCarrier.getParentId())
                    .eq(TMInquiryCarrier::getCarrierId, tmInquiryCarrier.getCarrierId())
                    .isNotNull(TMInquiryCarrier::getShippingCompany)
                    .list();
            List<TMInquiryCarrier> inquiryCarriers = tmInquiryCarriers.stream().filter(inquiryCarrier -> {
                return !(inquiryCarrier.getQuotationStatus().equals(EnquiryStatusEnum.FINISH.value()) ||
                        inquiryCarrier.getQuotationStatus().equals(EnquiryStatusEnum.DID_NOT_WIN_THE_BID.value()));
            }).collect(Collectors.toList());
            if (!inquiryCarriers.isEmpty()) {
                return R.status(true);
            }
            TMInquiryCarrier inquiryCarrier = iInquiryCarrierService.lambdaQuery()
                    .eq(TMInquiryCarrier::getParentId, tmInquiryCarrier.getParentId())
                    .eq(TMInquiryCarrier::getCarrierId, tmInquiryCarrier.getCarrierId())
                    .isNull(TMInquiryCarrier::getShippingCompany)
                    .one();
            inquiryCarrier.setQuotationStatus(EnquiryStatusEnum.FINISH.value());
            iInquiryCarrierService.updateById(inquiryCarrier);
        }
        return R.data(updateById);
    }

    //询价单是否回传sap
    public Boolean toSapInquiry(Long id) {
        List<TMInquiryCarrier> tmInquiryCarriers = iInquiryCarrierService.lambdaQuery()
                .eq(TMInquiryCarrier::getParentId, id)
                .list();
        List<TMInquiryCarrier> tmInquiryCarriers1 = iInquiryCarrierService.lambdaQuery()
                .eq(TMInquiryCarrier::getParentId, id)
                .and(tmInquiryCarrierLambdaQueryWrapper -> {
                    tmInquiryCarrierLambdaQueryWrapper
                            .eq(TMInquiryCarrier::getQuotationStatus, EnquiryStatusEnum.ABOLISHED.value())
                            .or().eq(TMInquiryCarrier::getQuotationStatus, EnquiryStatusEnum.DID_NOT_WIN_THE_BID.value())
                            .or().eq(TMInquiryCarrier::getQuotationStatus, EnquiryStatusEnum.FINISH.value());
                })
                .list();
        return tmInquiryCarriers.size() == tmInquiryCarriers1.size();
    }

    /**
     * @param id:
     * @return R<Boolean>
     * @author yr
     * @description 作废
     * @date 2022/7/5 11:36
     */
    public R<Boolean> invalid(Long id) {
        TMInquiryCarrier tmInquiryCarrier = iInquiryCarrierService.getById(id);
        tmInquiryCarrier.setQuotationStatus(EnquiryStatusEnum.ABOLISHED.value());
        boolean updateById = iInquiryCarrierService.updateById(tmInquiryCarrier);
        TMInquirySheet tmInquirySheet = iInquirySheetService.getById(tmInquiryCarrier.getParentId());
        if (tmInquirySheet.getWorkflowId().equals(EnquiryTypeEnum.foreignTrade.getValue())) {
            List<TMInquiryCarrier> tmInquiryCarriers = iInquiryCarrierService.lambdaQuery()
                    .eq(TMInquiryCarrier::getParentId, tmInquiryCarrier.getParentId())
                    .eq(TMInquiryCarrier::getCarrierId, tmInquiryCarrier.getCarrierId())
                    .isNotNull(TMInquiryCarrier::getShippingCompany)
                    .list();
            tmInquiryCarriers.forEach(inquiryCarrier -> {
                if (!inquiryCarrier.getQuotationStatus().equals((EnquiryStatusEnum.FINISH.value()))) {
                    inquiryCarrier.setQuotationStatus(EnquiryStatusEnum.DID_NOT_WIN_THE_BID.value());
                }
            });
            iInquiryCarrierService.updateBatchById(tmInquiryCarriers);
        }
        return R.data(updateById);
    }

    /**
     * 修改询价有效期和询价截止日期
     *
     * @param updateDateVO
     * @return
     */
    public R<String> updateDate(UpdateDateVO updateDateVO) {
        if (updateDateVO.getEndTime() == null || updateDateVO.getEffectiveTime() == null) {
            return R.fail("有效期或响应截止日期为空！");
        }
        TMInquirySheet tmInquirySheet = iInquirySheetService.getById(updateDateVO.getId());
        LocalDateTime endTime = updateDateVO.getEndTime();
        LocalDateTime effectiveTime = updateDateVO.getEffectiveTime();
        int compare1 = effectiveTime.compareTo(tmInquirySheet.getEffectiveTime());
        int compare2 = endTime.compareTo(tmInquirySheet.getEndTime());
        if (updateDateVO.getEndTime().isBefore(LocalDateTime.now()) && compare2 != 0) {
            return R.fail("修改后的截止日期不可小于当前时间！");
        }
        if (updateDateVO.getEffectiveTime().isBefore(LocalDateTime.now()) && compare1 != 0) {
            return R.fail("修改后的有效期不可小于当前时间！");
        }
        if (updateDateVO.getEndTime().isBefore(tmInquirySheet.getEndTime())) {
            return R.fail("修改后的截止日期不能小于当前截止日期");
        }
        if (updateDateVO.getEffectiveTime().isBefore(tmInquirySheet.getEffectiveTime())) {
            return R.fail("修改后的有效期不能小于当前有效期");
        }
        if (endTime != null && endTime.isAfter(tmInquirySheet.getEffectiveTime())) {
            CommonException.throwCommonException("响应截止日期不能大于询价有效期！");
        }
        if (effectiveTime != null && compare1 != 0) {
            tmInquirySheet.setEffectiveTime(effectiveTime);
            iInquirySheetService.updateById(tmInquirySheet);
            redisTemplate.opsForValue().set(INQUIRY_FORM_VOID + ExpirationReasonEnum.EXCEEDED_THE_VALIDITY_PERIOD_OF_THE_INQUIRY.getValue() + ":" + tmInquirySheet.getId(),
                    null, org.springblade.core.tool.utils.DateUtil.toDate(tmInquirySheet.getEffectiveTime()).getTime() - new Date().getTime(), TimeUnit.MILLISECONDS);
        }
        if (endTime != null && endTime.isBefore(tmInquirySheet.getEffectiveTime()) && compare2 != 0) {
            tmInquirySheet.setEndTime(endTime);
            iInquirySheetService.updateById(tmInquirySheet);
            redisTemplate.opsForValue().set(INQUIRY_FORM_VOID + ExpirationReasonEnum.RESPONSE_DEADLINE_EXCEEDED.getValue() + ":" + tmInquirySheet.getId(),
                    null, org.springblade.core.tool.utils.DateUtil.toDate(tmInquirySheet.getEndTime()).getTime() - new Date().getTime(), TimeUnit.MILLISECONDS);
            //修改已作废承运商报价状态为待报价
            List<TMInquiryCarrier> tmInquiryCarriers = iInquiryCarrierService.lambdaQuery()
                    .eq(TMInquiryCarrier::getParentId, updateDateVO.getId())
                    .eq(TMInquiryCarrier::getQuotationStatus, EnquiryStatusEnum.ABOLISHED.value())
                    .list();
            tmInquiryCarriers.forEach(tmInquiryCarrier -> {
                tmInquiryCarrier.setQuotationStatus(EnquiryStatusEnum.TO_BE_QUOTED.value());
            });
            iInquiryCarrierService.updateBatchById(tmInquiryCarriers);
        }

        return R.data("修改成功！");
    }


    public R<List<CarrierListVO>> priceCarrierList(Long id) {
        List<TMInquiryCarrier> inquiryCarriers = iInquiryCarrierService.lambdaQuery()
                .select(TMInquiryCarrier::getQuotationStatus, TMInquiryCarrier::getCarrierName)
                .eq(TMInquiryCarrier::getParentId, id)
                .isNull(TMInquiryCarrier::getShippingCompany)
                .list();
        List<CarrierListVO> carrierListVOS = BeanUtil.copy(inquiryCarriers, CarrierListVO.class);
        BigDecimal bigDecimal = BigDecimal.valueOf(1);
        carrierListVOS.forEach(carrierListVO -> {
            carrierListVO.setSerialNo(bigDecimal.add(BigDecimal.valueOf(1)));
            carrierListVO.setQuotationStatus(EnumUtils.getEnumByValue(EnquiryStatusEnum.class, carrierListVO.getQuotationStatus()).get().description());
        });
        return R.data(carrierListVOS);
    }
}
